package com.raindrop.utils;

import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * Created by liuhang on 2017/11/17.
 * 序列化工具
 */

public class SequenceUtil {
    private static final String PRI_STR = "Rd";

    public static String getNewNumber() {
        String str = PRI_STR + System.currentTimeMillis() + UUID.randomUUID().toString();
        return Base64.encodeBase64String(encrypt16(str).getBytes());
    }

    private static String encrypt32(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    private static String encrypt16(String encryptStr) {
        return encrypt32(encryptStr).substring(8, 24);
    }
}
